package physicsSimTest;

public class Collision implements Comparable<Collision>{
	double time, millis; //Percent, E(0, 1)
	Particle p1, p2;
	Vector posV;
	
	public Collision(double t, Particle pA, Particle pB, Vector pV, double ms){
		time = t;
		p1 = pA;
		p2 = pB;
		posV = pV;
		millis = ms;
	}
	
	public void runCollide(){
		Vector vToCol1 = Vector.scalarMultiply(time, p1.getRemainingVelocity());
		Vector vToCol2 = Vector.scalarMultiply(time, p2.getRemainingVelocity());
		p1.x+= vToCol1.x*millis;
		p2.y+= vToCol1.y*millis;
		p1.x+=vToCol2.x*millis;
		p2.y+=vToCol2.y*millis;
		p1.reduceRemainingVelocity(1-time);
		p2.reduceRemainingVelocity(1-time);
		//Calculating Bounce
		Vector n = Vector.normal(Vector.scalarMultiply(-1,posV));
		float a1 = (float) Vector.dotProduct(p1.getActualVelocity(), n);
		float a2 = (float) Vector.dotProduct(p2.getActualVelocity(), n);
		float optimizedP = (float) (2 * (a1 - a2) / (p1.getMass() + p2.getMass())); // Mass of each ball is 1
		Vector newV1 = Vector.subtract(p1.getActualVelocity(),
				Vector.scalarMultiply(optimizedP * p2.getMass(), n));
		Vector newV2 = Vector.add(p2.getActualVelocity(),
				Vector.scalarMultiply(optimizedP * p1.getMass(), n));
		newV1 = Vector.scalarMultiply(0.95, newV1);
		newV2 = Vector.scalarMultiply(0.95, newV2);
		System.out.println("BEFORECOL: "+Vector.getMagnitude(p2.getActualVelocity())+Vector.getMagnitude(p1.getActualVelocity()));
		p1.changeVelocityByActual(newV1);
		p2.changeVelocityByActual(newV2);
		System.out.println("AFTERCOL: "+Vector.getMagnitude(p2.getActualVelocity())+Vector.getMagnitude(p1.getActualVelocity()));
		
		p1.roundDownVelocity(3);
		p2.roundDownVelocity(3);
	}

	@Override
	public int compareTo(Collision o) {
		if(time<o.time)
			return -1;
		return 1;
	}
}
